#include "../s21_decimal.h"

int s21_floor(s21_decimal value, s21_decimal *result) {
  if (s21_is_invalid(&value) || result == NULL) {
    return ERROR;
  }

  int number = s21_truncate_private(&value, result);

  if (s21_get_sign(&value) == NEGATIVE && number > 0) {
    s21_increase_by_one(result);
  }

  return OK;
}

int s21_round(s21_decimal value, s21_decimal *result) {
  if (s21_is_invalid(&value) || result == NULL) {
    return ERROR;
  }

  int number = s21_truncate_private(&value, result);

  if (number > 0) {
    int discarded_digit = number % 10;
    int discarded_digits_sum = number / 10;
    int is_not_even = s21_get_bit(result, 0) == 1 ? TRUE : FALSE;

    if (discarded_digit > 5 ||
        (discarded_digit == 5 && discarded_digits_sum > discarded_digit) ||
        (discarded_digit == 5 && discarded_digits_sum == 5 && is_not_even)) {
      s21_increase_by_one(result);
    }
  }

  return OK;
}

int s21_truncate(s21_decimal value, s21_decimal *result) {
  if (s21_is_invalid(&value) || result == NULL) {
    return ERROR;
  }

  s21_truncate_private(&value, result);

  return OK;
}

int s21_negate(s21_decimal value, s21_decimal *result) {
  if (s21_is_invalid(&value) || result == NULL) {
    return ERROR;
  }

  s21_copy(&value, result);
  s21_inverse_sign(result);

  return OK;
}